package com.webchat.client.mall.filter;

import com.webchat.client.mall.service.UserSessionService;
import com.webchat.common.helper.SessionHelper;
import com.webchat.rmi.sso.OauthServiceClient;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author: 程序员七七
 * @Date: 16.11.21 11:26 下午
 */
@Slf4j
@Order(-6)
@WebFilter(filterName = "oauthFilter", urlPatterns = {"/*"})
@Component
public class OauthFilter implements Filter {

    @Autowired
    private OauthServiceClient oauthServiceClient;

    @Autowired
    private UserSessionService userSessionService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 取集中session服务判断是否已经登录，如果已经登录则直接进入后续方法。
        String userId = userSessionService.getUserIdByBizToken(request);
        if (StringUtils.isBlank(userId)) {
            // 获取泛域名下SSO登录用户
            userId = userSessionService.getUserIdBySSOToken(request);
            if (StringUtils.isBlank(userId)) {
                // 基于Oauth认证
                String oauthCode = request.getHeader("oauth-code");
                if (StringUtils.isNotBlank(oauthCode)) {
                    userId = oauthServiceClient.getUserIdByOauthCode(oauthCode).getData();
                }
            }
            // 本地 token 用户认证失败，但是基于SSO/oauth认证成功，重新种本地cookie
            if (StringUtils.isNotBlank(userId)) {
                userSessionService.createUserLoginSession(response, userId);
            }
        }
        if (StringUtils.isNotBlank(userId)) {
            // 获取到了登录信息，保存到当前线程副本
            SessionHelper.setUserId(userId);
        }
        try {
            // 不论登录与否，都正常执行后续流程
            filterChain.doFilter(request, response);
        } finally {
            SessionHelper.clear();
        }
    }

    @Override
    public void destroy() {

    }
}
